package com.itstudy.common;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

import java.util.List;

/**
 * @ClassName: RpcDecoder
 * @Auther: Jerry
 * @Date: 2020/8/18 22:40
 * @Desctiption: TODO
 * @Version: 1.0
 */
public class RpcDecoder extends ByteToMessageDecoder {

    private Class<?> clazz;
    private Serializer serializer;

    public RpcDecoder(Class<?> clazz, Serializer serializer) {
        this.clazz = clazz;
        this.serializer = serializer;
    }

    @Override
    protected void decode(ChannelHandlerContext channelHandlerContext,
                          ByteBuf byteBuf, List<Object> list) throws Exception {
        byteBuf.markReaderIndex();
        // 读取消息长度
        int len = byteBuf.readInt();
        // 如果可以读的数据小于协议中的数据，需要重置一下读的下标，重新读取
        if (byteBuf.readableBytes() < len) {
            byteBuf.resetReaderIndex();
            return;
        }
        byte[] bytes = new byte[len];
        // 将读取的字节填充到空的数组中
        byteBuf.readBytes(bytes);

        Object obj = serializer.deserialize(clazz, bytes);
        // 将传输的字节数组转换为字符串传递给下一个入站类处理
        list.add(obj);
    }
}
